package com.chen.weather;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class CityReader {

    private String path;

    public CityReader(String path) {
        this.path = path;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public List<City> read() throws FileNotFoundException, IOException {
        List<City> citys = new ArrayList<>();
        if (this.path == null || this.path.isEmpty()) {
            return citys;
        }
        File file = new File(this.path);
        if (file.isDirectory()) {
            return citys;
        }

        FileReader reader = new FileReader(file);
        StringBuilder buffer = new StringBuilder();
        char[] buff = new char[2048];

        int size;
        do {
            size = reader.read(buff, 0, buff.length);
            if (size > 0) {
                buffer.append(buff, 0, size);
            }
        } while (size != -1);

        Gson gson = new Gson();
        List cityList = gson.fromJson(buffer.toString(), List.class);
        for (Iterator it = cityList.iterator(); it.hasNext();) {
            Object city = it.next();
            if (city instanceof LinkedTreeMap) {
                LinkedTreeMap name = (LinkedTreeMap) city;
                citys.add(new City(
                        (double) name.get("_id"),
                        (double) name.get("id"),
                        (double) name.get("pid"),
                        (String) name.get("city_code"),
                        (String) name.get("city_name"))
                );
            }
        }
        return citys;
    }
}
